import axios from "axios"
import router from "@/router"
import { TOKEN } from "@/constants"
import i18n from "@/i18n"
import type { AxiosRequestConfig } from "axios"

const { t } = i18n.global

const instance = axios.create({
  baseURL: "http://192.168.10.13:8878/api",
  timeout: 10000,
  withCredentials: true
})

instance.interceptors.request.use(
  (config) => {
    // 获取 Token
    const token = localStorage.getItem(TOKEN)
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }

    return config
  },
  (err) => {
    return err
  }
)

instance.interceptors.response.use(
  (res) => {
    const data = res.data

    if (data.code !== 1) {
      throw new Error(data.message ?? data.msg)
    }

    return data
  },
  (err) => {
    if (!err.response) {
      throw new Error(t("error.networkError"))
    }

    if (err.response.status === 401) {
      localStorage.removeItem(TOKEN)
      router.replace("/login")
      throw new Error(t("error.authExpired"))
    }

    if (err.response.status === 403) {
      throw new Error("权限不足，请联系管理员")
    }

    if (
      err.response.status === 500 ||
      err.response.status === 502 ||
      err.response.status === 503 ||
      err.response.status === 504
    ) {
      throw new Error(t("error.serverError"))
    }

    return err
  }
)

function request<T>(config: AxiosRequestConfig) {
  return new Promise<Result<T>>((resolve, reject) => {
    instance
      .request<any, Result<T>>(config)
      .then((res) => resolve(res))
      .catch((err) => reject(err))
  })
}

function get<T = any>(config: AxiosRequestConfig) {
  return request<T>({ ...config, method: "GET" })
}

function post<T = any>(config: AxiosRequestConfig) {
  return request<T>({ ...config, method: "POST" })
}

export { get, post }
